#include <iostream>
#include <pthread.h>
using namespace std;

int ticket = 1000;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void* Buy_Ticket(void* arg)
{
    int id = *(int*)arg;
    while (1)
    {
        pthread_mutex_lock(&mutex);
        if (ticket > 0)
        {
            ticket--;
            cout << "pthread id: " << id << " buy ticket, Remaining ticket: " << ticket << endl;
        }
        else
        {
            cout << "Thread " << id << " finished selling tickets" << endl;
            pthread_mutex_unlock(&mutex); // 解锁
            break;
        }
        pthread_mutex_unlock(&mutex);
    }
    return nullptr;
}

int main()
{
    pthread_t threads[5];
    int threads_id[5];
    for (int i = 0; i < 5; i++)
    {
        threads_id[i] = i + 1;
        pthread_create(&threads[i], nullptr, Buy_Ticket, &threads_id[i]);
    }

    for (int i = 0; i < 5; i++)
    {
        pthread_join(threads[i], nullptr);
    }

    pthread_mutex_destroy(&mutex);

    return 0;
}